<%-- 
   * 【描 述】：角色管理页面
   * 【环 境】：JAVA 1.7.0_13
   *  @author         柴志鹏  CHAIZP@GMAIL.COM
   *  @version        v1.0 2014-06-10
   *  @since          2014-06-10
 --%>
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%@ include file="/include/head.jsp"%>
<html>
  <head>
    <title>角色管理</title>
    <script src="<%=jsPath%>/expand/TreeCheckNodeUI.js" type="text/javascript"></script>
    <script type="text/javascript">
    	var roleId = null;//角色ID
    	Ext.onReady(function() {
    		Ext.QuickTips.init();
	    	Ext.form.Field.prototype.msgTarget = 'qtip';
	    	
	    	var westStore = new Ext.data.Store({//角色数据源
				proxy: new Ext.data.HttpProxy({
					url: 'RoleAction!getRoleList.do'
				}),
				reader: new Ext.data.JsonReader({
					totalProperty: 'total',
					root: 'list'
				}, new Ext.data.Record.create([
					{name: 'cudType'},
					{name: 'id'},
		        	{name: 'roleName'},
				    {name: 'enableStatus'},
				    {name: 'remark'}
				])),
				//sortInfo: {field: 'id', direction: 'ASC'},
				remoteSort: false,//是否远程排序
				autoLoad: {
					params:{
						start: PAGING_START_INDEX,
						limit: PAGING_PAGE_SIZE
					}
				}
			});
	    	
	    	var centerStore = new Ext.data.Store({//菜单数据源
				proxy: new Ext.data.HttpProxy({
					url: 'RoleAction!getRelationMenuList.do'
				}),
				reader: new Ext.data.JsonReader({
					totalProperty: 'total',
					root: 'list'
				}, new Ext.data.Record.create([
					{name: 'id'},
		        	{name: 'text'},
				    {name: 'enableStatus'},
				    {name: 'roleId'},
				    {name: 'menuId'}
				])),
				remoteSort: false,
				autoLoad: false
			});
	    	
	    	var westModel = new Ext.grid.CheckboxSelectionModel({
	    		singleSelect: true,//单选
	    		header: '',//空来代替checkbox全选框
		    	listeners: {
	    			rowselect: function(selModel, rowIndex, record) {//行选中
	    				roleId = record.get('id');
	    				centerStore.baseParams = {
			        		roleId: roleId
	    				};
	    				centerStore.reload({
	    					params: {
	    						start: PAGING_START_INDEX,
								limit: PAGING_PAGE_SIZE
	    					}
	    				});
	    			}
		    	}
		    });
	    	
	    	var westCol = new Ext.grid.ColumnModel({
	    		defaults: {
		            sortable: true // 默认全部列可排序          
		        },
		        columns: [
		        	westModel,
		        	new Ext.grid.RowNumberer({
		        		id: 'rownum',
		        		header: '序号',
						width: 50,
						align: 'center'	
					}),{
		        		id: 'roleId',
						header: '主键ID',
						dataIndex: 'id',
						width: 25,
						align: 'center',
						hidden: true
						//sortable: true
					},{
		        		id: 'roleName',
			        	header: cf_getRequiredItem('角色名称'),
			        	dataIndex: 'roleName',
			      		width: 80,
			           	align: 'center',
			           	editor: new Ext.form.TextField({
			           		maxLength: 20,
		           			maxLengthText: '名称长度不可大于{0}字符',
			            	allowBlank: false,
			            	blankText: '必填项不可为空!'
			           	})
			        },{
		        		id: 'remark',
			        	header: '备注',
			        	dataIndex: 'remark',
			      		width: 130,
			           	align: 'center',
			           	editor: new Ext.form.TextField(),
			           	renderer: function(value, metadata, record, rowIndex, colIndex, store) {
			        		metadata.attr = 'ext:qtip="'+ value +'"';
			        		return value;
			        	}
			        },{
			        	id: 'enableStatus',
			        	header: cf_getRequiredItem('状态'),
			        	dataIndex: 'enableStatus',
			        	width: 60,
			        	align: 'center',
			        	editor: new Ext.form.ComboBox({
							typeAhead: true,
							editable: false,
							store: new Ext.data.SimpleStore({
								id: 'enableStatusStore',
								fields: ['code', 'value'],
								data:[['1','启用'],['0','禁用']]
							}),
							displayField: 'value',
							valueField: 'code',               
							triggerAction: 'all',
							mode: 'local'
			        	}),
			        	renderer: function(value, cellmeta, record) {
			        		if(value){
			        			var editor = this.getEditor();
								var index = editor.getStore().find(editor.valueField, value);
								var record = editor.getStore().getAt(index); 
								return ['<span style="color:red;font-weight:bold;">禁用</span>',
			        				'<span style="color:green;font-weight:bold;">启用</span>']
			        				[record.data.code];
							}
			        	}
			        }
		        ]
		    });
	    	
	    	
	    	
	    	var centerModel = new Ext.grid.CheckboxSelectionModel();
	    	var centerCol = new Ext.grid.ColumnModel({
	    		defaults: {
		            sortable: true // 默认全部列可排序          
		        },
		        columns: [
		        	centerModel,
		        	new Ext.grid.RowNumberer({
		        		id: 'rownum',
		        		header: '序号',
						width: 50,
						align: 'center'	
					}),{
		        		id: 'menuId',
						header: '主键ID',
						dataIndex: 'id',
						width: 25,
						align: 'center',
						hidden: true
						//sortable: true
					},{
		        		id: 'menuName',
			        	header: '菜单名称',
			        	dataIndex: 'text',
			      		width: 80,
			           	align: 'center'
			        },{
			        	id: 'enableStatus',
			        	header: '状态',
			        	dataIndex: 'enableStatus',
			        	width: 50,
			        	align: 'center',
			        	renderer: function(value, cellmeta, record) {
			        		if(value) {
			        			return ['<span style="color:red;font-weight:bold;">禁用</span>',
				        				'<span style="color:green;font-weight:bold;">启用</span>']
				        				[value];
							}
			        	}
			        }
		        ]
		    });
//==================================================
	    	var viewport = new Ext.Viewport({
	    		layout: 'border',
	    		items:[
	    			new Ext.grid.EditorGridPanel({
			        	region: 'west',//西
			        	id: 'westViewport',
				        autoScroll: true,
					    store: westStore,
					    cm: westCol,
					    sm: westModel,
					    //autoExpandColumn: 'roleName', // column with this id will be expanded
					    frame: false,
					    trackMouseOver: true,//鼠标经过痕迹
					    //clicksToEdit: 1,
					    loadMask: true,
			        	loadMask: {msg: 'loading...'},
					    tbar: [{
					        text: '新增',
					        iconCls: 'addBtn',
					        handler : function() {
					    		var RecordSet = Ext.data.Record.create([
						    	   {name: 'cudType'},
						    	   {name: 'id'},
						    	   {name: 'roleName'},
						    	   {name: 'remark'},
						    	   {name: 'enableStatus'}
							    ]);
					    		var recordSet = new RecordSet({
				            		cudType: 'C',
				            		id: '',
				            		roleName:'',
				            		remark: '',
				            		enableStatus: '1'
				            	});
					    		
					    		var westGrid = Ext.getCmp('westViewport');
				            	westGrid.stopEditing();
								westGrid.getStore().insert(0, recordSet);
								westGrid.startEditing(0, 3);
								for(var i = 0; i < westGrid.getStore().getCount(); i++){ //使RowNumberer加1
									if(Ext.isIE) {
										westGrid.getView().getCell(i, westCol.getIndexById('rownum')).firstChild.innerText = i + 1;
									} else {
										westGrid.getView().getCell(i, westCol.getIndexById('rownum')).firstChild.textContent = i + 1;
									}
								}
								westGrid.getSelectionModel().selectFirstRow();
					        }
					    },{
					        text: '删除',
					        iconCls: 'deleteBtn',
					        handler : function() {
					    		var westGrid = Ext.getCmp('westViewport');
					    		var records = westGrid.getSelectionModel().getSelections();
					    		if(records.length > 0) {
				                    for (var i = 0, len = records.length; i < len; i++) {
							       		records[i].data['cudType'] = 'D';	                    
					                    if (westGrid.getStore().modified.indexOf(records[i]) == -1)
					                   		westGrid.getStore().modified.push(records[i]);
				                        westGrid.getStore().remove(records[i]);
				                    }	            	
				            	} else {
				            		Ext.MessageBox.alert('提示', '请选择一条记录');
				            	}
					        }
					    },{
					        text: '保存',
					        iconCls: 'saveBtn',
					        handler : function() {
					    		var records = westStore.getModifiedRecords();
						        if (records.length > 0) {
						        	if(!cf_validateGrid(Ext.getCmp('westViewport'), westCol, ['roleName']))
										return;
							        Ext.MessageBox.confirm('提示', '确认保存?',
										function(btn) {
										    if(btn == BUTTON_YES) {
										    	cf_ShowMessageBox('保存中..');
										        var data = "[";
										        for (var i = 0, len = records.length; i < len; i++){
										            data = data + "{cudType:'" + records[i].get('cudType') +
									            		"', id:'" + records[i].get('id') + 
									            		"', roleName:'" + records[i].get('roleName') + 
									            		"', remark:'" + records[i].get('remark') + 
									            		"', enableStatus:'" + records[i].get('enableStatus') + 
									            		"'}";
										            if (i < len - 1) {data = data + ",";}
										        }
												data = data + "]";
												
												Ext.Ajax.request({
													url: 'RoleAction!roleOperator.do',
													method: 'POST',
													params: {jsonData: data},
													success: function (result, request) {
														Ext.MessageBox.alert('提示', '操作成功!',
															function(btn) {
																refresh('west');
															}
														);
													},
													failure: function (result, request) {
														Ext.MessageBox.alert('提示', '操作失败!');
										            }
												});
								         	}
										}
							        );
						        } else {
						            Ext.MessageBox.alert('提示', '没有任何数据改变.');
						            return false;			        
						        }
					        }
					    },'->','角色名',
				        	new Ext.form.TwinTriggerField({
							    trigger1Class: 'x-form-clear-trigger',
							    trigger2Class: 'x-form-search-trigger',
							    hideTrigger1: true,
							    autoWidth: true,
							    listeners: {
							        'specialkey': function(f, e){
							        	if(e.getKey() == e.ENTER){
							            	this.onTrigger2Click();
							        	}
							    	}
							 	},
							 	onTrigger1Click:function(){
							    	this.setRawValue('');
							     	this.triggers[0].hide();
							    	return false;
							 	},
							 	onTrigger2Click:function(){
							    	var name = this.getRawValue().replace(/(^\s*)|(\s*$)/g, "");//去前后空格
						        	this.triggers[0].show();
							    	westStore.baseParams = {
										roleName: name
									}
							        westStore.reload({
							        	params: {
							        		start: PAGING_START_INDEX,
											limit: PAGING_PAGE_SIZE
							        	}
							    	});
								}
							})
					    ],
					    bbar: cf_getPagingToolbar(PAGING_PAGE_SIZE, westStore),
					    viewConfig: {
			        		forceFit: true,//根据column进行百分比设置
			        		scrollOffset: 0//不加这个的话，会在grid的最右边有个空白，留作滚动条的位置。若不加默认为scrollOffset: 20
			        	},
			        	listeners: {
			        		afteredit: function(e) {
			        			var record = e.record;
					       		if (record.get('cudType') == undefined || record.get('cudType') == '') {
					       			record.data['cudType'] = 'U';
					       		}
								record.dirty = true;
								record.modified = e.record;
								if (westStore.modified.indexOf(record) == -1) {
									westStore.modified.push(record);
								}
			        		},
			        		afterrender: function(grid) {
			        			setTimeout(function(){//渲染速度问题延迟500毫秒
			        				if(westStore.getCount() > 0) {//默认选中首行
				        				grid.getSelectionModel().selectRow(0);
				        			}
			        			}, 500);
			        		}
			        	}
					}),
					new Ext.grid.GridPanel({
						id: 'centerViewport',
				        region: 'center',
				        autoScroll: true,
				        store: centerStore,
					    cm: centerCol,
					    sm: centerModel,
					    frame: false,
					    trackMouseOver: true,//鼠标经过痕迹
					    //clicksToEdit: 1,
					    loadMask: true,
			        	loadMask: {msg: 'loading...'},
			        	tbar: [{
			        		text: '菜单授权',
					        iconCls: 'addBtn',
					        handler : function() {
			        			var record = Ext.getCmp('westViewport').getSelectionModel().getSelected();
			        			if(record != undefined) {
			        				menuAuthorization(record.id);
			        			} else {
			        				Ext.MessageBox.alert('提示','请选择授权的角色!');
			        			}
			        		}
			        	},{
			        		text: '取消授权',
					        iconCls: 'deleteBtn',
					        handler : function() {
			        			var records = Ext.getCmp('centerViewport').getSelectionModel().getSelections();
						        if (records.length > 0) {
							        Ext.MessageBox.confirm('提示', '确认删除?',
										function(btn) {
										    if(btn == BUTTON_YES) {
										    	cf_ShowMessageBox('删除中..');
										        var data = "[";
										        for (var i = 0, len = records.length; i < len; i++){
										            data = data + "{roleId:'"+ records[i].get('roleId') +
										            	"', menuId:'" + records[i].get('menuId') +"'}";
										            if (i < len - 1) {	data = data + ",";}
										        }
												data = data + "]";
												
												Ext.Ajax.request({
													url: 'RoleAction!deleteRelationMenu.do',
													method: 'POST',
													params: {jsonData: data},
													success: function (result, request) {
														Ext.MessageBox.alert('操作成功', '共：'+ result.responseText +'条菜单被取消授权.',
															function(btn) {
																refresh('center');
															}
														);
													},
													failure: function (result, request) {
														Ext.MessageBox.alert('提示', '操作失败!');
										            }
												});
								         	}
										}
							        );
						        } else {
						            Ext.MessageBox.alert('提示', '请选择要取消授权的菜单.');
						            return false;			        
						        }
					        }
			        	},'->','菜单名',
				        	new Ext.form.TwinTriggerField({
							    trigger1Class: 'x-form-clear-trigger',
							    trigger2Class: 'x-form-search-trigger',
							    hideTrigger1: true,
							    width: 100,
							    listeners: {
							        'specialkey': function(f, e){
							        	if(e.getKey() == e.ENTER){
							            	this.onTrigger2Click();
							        	}
							    	}
							 	},
							 	onTrigger1Click:function(){
							    	this.setRawValue('');
							     	this.triggers[0].hide();
							    	return false;
							 	},
							 	onTrigger2Click:function(){
							    	var name = this.getRawValue().replace(/(^\s*)|(\s*$)/g, "");//去前后空格
						        	this.triggers[0].show();
							    	var record = Ext.getCmp('westViewport').getSelectionModel().getSelected();
							    	centerStore.baseParams = {
						        		roleId: record.id
				    				};
							        centerStore.reload({
							        	params: {
							        		start: PAGING_START_INDEX,
											limit: PAGING_PAGE_SIZE,
							        		menuName: name
							        	}
							    	});
								}
							})
			        	],
			        	bbar: cf_getPagingToolbar(PAGING_PAGE_SIZE, centerStore),
					    viewConfig: {
			        		forceFit: true,//根据column进行百分比设置
			        		scrollOffset: 0//不加这个的话，会在grid的最右边有个空白，留作滚动条的位置。若不加默认为scrollOffset: 20
			        	}
					})
	    		],
			    listeners: {
					resize: function(viewport, adjWidth, adjHeight, rawWidth, rawHeight) {
	    				var westView = Ext.getCmp('westViewport');
	    				if(Ext.isIE) {
	    					westView.setWidth((adjWidth=='auto'?700:adjWidth)*0.55);
	    				} else {
	    					westView.setWidth('55%');
	    				}
					}
				}
	    	});

			function menuAuthorization(roleId) {
				var win = new Ext.Window({
		            title: '功能菜单',
		            id: 'menuWin',
		            width: 250,
		            height: 400,
		            modal: true,
		            closeAction: 'close',
		            resizable: true,
		            constrain: false,//禁止窗口移出浏览器
					constrainHeader: true,//禁止窗口移出浏览器
		            items: new Ext.form.FormPanel({
	            		id: 'menuForm',
	            		border: false,
	            		buttonAlign: 'center',
	            		layout: 'accordion',
			            layoutConfig: {
		                    animate: true
		                },
	            		items: [
	            			new Ext.Panel({
				                title: '用户菜单',
				                collapsed: false,
				                items: [new TreePanel({
				                	id: 'userMenuTree',
				                	menuType: '1'
				                })]
				            }), new Ext.Panel({
				                title: '设置菜单',
				                collapsed: true,
				                items: [new TreePanel({
				                	id: 'settingsMenuTree',
				                	menuType: '2'
				                })]
				        	})
	            		],
	            		buttons: [{
	            			text:'保存',
	            			handler : function() {
	            				var records = filterDupFunctionRecord(array);
	            				if (array.length < 1 || records.length < 1) {
						       		Ext.MessageBox.alert('提示', '数据没有任何改变!');
						       		return false;
						       	}
	            				cf_ShowMessageBox('保存中..');
						       	var data = "[";
						       	for(var i = 0,len = records.length; i < len; i++) {
						       		data = data + "{roleId:'" + records[i].get('roleId') +
						       				"', menuId:'" + records[i].get('menuId') +
						       				"', checked:'" + records[i].get('checked') +
						            		"'}";
						            if (i < len - 1) {data = data + ",";}
						       	}
						       	data = data + "]";
						       	
						       	Ext.Ajax.request({
									url: 'RoleAction!relationMenuController.do',
									method: 'POST',
									params: {jsonData: data},
									success: function (){
										Ext.MessageBox.alert('提示', '操作成功',
										function(btn) {
											var menuWin = Ext.getCmp('menuWin');
											menuWin.hide('roleManager', function(){
												refresh('center');
												menuWin.close();
											} ,true);
										});
									},
									failure: function (){
										Ext.MessageBox.alert('提示', '操作失败');
						            }
								});	
	            			}
	            		},{
	            			text:'取消',
	            			handler: function() {
	            				win.hide('roleManager', function() {	// 淡入窗口
			                    	win.close();						// 关闭
			                    }, true);
	            			}
	            		}]
		            }),
		            listeners: {
	                	beforerender: function(win) {
	                		Ext.getCmp('menuForm').setHeight(win.height-30);
	                	}
            		}
		        });
		        win.show('roleManager');// 淡出窗口
			}

			function refresh(type) {
				if(type == 'west') {
					westStore.modified = [];
		           	westStore.removeAll();
		  			westStore.reload();
				} else {
					centerStore.modified = [];
		           	centerStore.removeAll();
		  			centerStore.reload();
				}
	    	}

    	});
    	
    	function filterDupFunctionRecord(receiveArray) {//过滤数组中的重复记录
		    var arrResult = new Array();//定义一个返回结果数组
		    for (var i = 0; i < receiveArray.length; i++) {
		        if (isDuplicateFunction(arrResult, receiveArray[i]) == -1) {//把不重复的记录放入新数组
		            arrResult.push(receiveArray[i]);
		        } else {//重复的记录取最后一个,因为要获得最后的选项
		        	arrResult.removeAt(isDuplicateFunction(arrResult, receiveArray[i]));
		        	arrResult.insert(i,receiveArray[i]);
		        }
		    }
		    return arrResult;
		}
    	
    	function isDuplicateFunction(receiveArray, checkItem) { //判断记录是否重复
		    var index = -1;  // 函数返回值用于布尔判断
		    for (var i = 0; i < receiveArray.length; i++) {
		        if (receiveArray[i].get('menuId') == checkItem.get('menuId')) {
		            index = i; //如果重复,返回当前index
		            break;
		        }
		    }
		    return index;
		}
    	
    	var array = new Array();
    	
    	var TreePanel = Ext.extend(Ext.tree.TreePanel, {
    		constructor: function(config) {
    			var MenuRecordSet = Ext.data.Record.create([
		    		{name: 'id'},
				   	{name: 'roleId'},
				   	{name: 'menuId'},
				   	{name: 'checked'}
				]);
    			config = Ext.apply({
    				id: this.id,
                	useArrows: true,
			        autoScroll: false,
			        animate: true,
			        enableDD: false,//拖拽
			        containerScroll: true,
			        checkModel: 'cascade',//多选: 'multiple'(默认) 单选: 'single' 级联多选: 'cascade'(同时选父和子);'parentCascade'(选父);'childCascade'(选子)  
			        border: false,
			        rootVisible: false,
			        loader: new Ext.tree.TreeLoader({
			        	baseAttrs: { uiProvider: Ext.ux.TreeCheckNodeUI }
			        }),
			        root: new Ext.tree.AsyncTreeNode({
				        id: '0',//pid
				        //text: '菜单',
				        draggable: false,// 根节点不容许拖动
				        expanded: false
				    }),
			        listeners: {
		    			beforeload: function(node) {//加载之前
			        		var record = Ext.getCmp('westViewport').getSelectionModel().getSelected();
                			this.loader.dataUrl = 'RoleAction!queryRelationMenu.do?menuType='+ this.menuType +'&pid='+ node.id +'&roleId='+ record.id;
				        },
				        check: function(node, checked) {
				        	array.push(new MenuRecordSet({
				        		roleId: roleId,
				        		menuId: node.id,
				        		checked: checked
				        	}));
				        }
			        }
		        }, config);
		        TreePanel.superclass.constructor.call(this, config);
    		}
    	});
    </script>
  </head>
  
  <body>
    <div id="roleManager"></div>
  </body>
</html>
